package com.lxy.cxcyxmmsbackend.sys.controller;


import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxy.cxcyxmmsbackend.sys.entity.*;
import com.lxy.cxcyxmmsbackend.sys.exceptionHandle.exce.NormalException;
import com.lxy.cxcyxmmsbackend.sys.req.PageReq;
import com.lxy.cxcyxmmsbackend.sys.res.Result;
import com.lxy.cxcyxmmsbackend.sys.service.*;
import com.lxy.cxcyxmmsbackend.sys.utils.UUIDUtil;
import com.lxy.cxcyxmmsbackend.sys.utils.UpPhotoNameUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * 创新创业项目
 *
 * @author 刘新颖
 * @since 2024-01-07
 */
@Api(tags = "创新创业项目")
@RestController
@RequestMapping("/cxcyXm")
public class CxcyXmController {

    @Resource
    CxcyXmService cxcyXmService;

    @Autowired
    XmCyService xmCyService;

    @Autowired
    QxglUserService qxglUserService;

    @Autowired
    XmHjqkService xmHjqkService;

    @Autowired
    KeyValueService keyValueService;

    @Autowired
    Environment environment;

    @ApiOperation("模糊分页查询项目信息")
    @RequestMapping("queryCxcyXmList")
    public Result queryCxcyXmList(@RequestBody PageReq pageReq) {

        Integer limitS = pageReq.getCurrentPage();
        Integer pageS = pageReq.getPageSize();
        Page<CxcyXm> pages = new Page<>(limitS, pageS);
        QueryWrapper<CxcyXm> wrapper = new QueryWrapper<>();

        String xmmc = pageReq.getKeyWord().get("xmmc");
        String xmzt = pageReq.getKeyWord().get("xmzt");
        String xmkjhm = pageReq.getKeyWord().get("xmkj");
        String xmlx = pageReq.getKeyWord().get("xmXmlxbh");
        //项目名称
        if (xmmc != null && !"".equals(xmmc)) {
            wrapper.lambda().like(CxcyXm::getXmMc, xmmc);
        }

        //项目状态
        if (xmzt != null && !"".equals(xmzt)) {
            wrapper.lambda().eq(CxcyXm::getXmzt, xmzt);
        }

        //项目房间
        if (xmkjhm != null && !"".equals(xmkjhm)) {
            wrapper.lambda().like(CxcyXm::getXmKjhm, xmkjhm);
        }

        //项目类型
        if (xmlx != null && !"".equals(xmlx)) {
            wrapper.lambda().eq(CxcyXm::getXmXmlxbh, xmlx);
        }
        wrapper.lambda().isNotNull(CxcyXm::getXmzt);
        IPage<CxcyXm> page = cxcyXmService.page(pages, wrapper);

        HashMap<Object, Object> map = new HashMap<>();

        map.put("pageNo", limitS);
        map.put("pageSize", pageS);
        map.put("rows", page.getRecords());
        map.put("total", page.getTotal());
        map.put("pageNums", (int) Math.ceil((double) page.getTotal() / pageS));

        return Result.success("查询项目列表成功", map);
    }

    @ApiOperation("查询项目详情信息")
    @GetMapping("/queryCxcyXmByBh/{xmBh}")
    public Result queryCxcyXmByBh(@PathVariable("xmBh") String xmBh) {
        HashMap<String, Object> resultMap = new HashMap<>();
        //基本信息
        CxcyXm cxcyXm = cxcyXmService.getById(xmBh);

        //项目成员
        QueryWrapper<XmCy> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(XmCy::getXmBh, xmBh);
        List<XmCy> xmcyList = xmCyService.list(wrapper);

        QueryWrapper<XmHjqk> wrapper2 = new QueryWrapper<>();
        wrapper2.lambda().eq(XmHjqk::getXmBh, xmBh);
        List<XmHjqk> xmHjqkList = xmHjqkService.list(wrapper2);

        resultMap.put("xmDetail", cxcyXm);
        resultMap.put("xmcyList", xmcyList);
        resultMap.put("xmHjqkList", xmHjqkList);
        if (cxcyXm == null) {
            throw new NormalException("查询项目详情信息失败");
        }
        return Result.success("查询项目详情信息成功", resultMap);
    }

    @ApiOperation("保存或申报创新创业项目信息")
    @PostMapping("/cxcyxmShenBao")
    public Result cxcyxmShenBao(@RequestBody CxcyXm cxcyXm, HttpServletRequest request) {
        String userBh = request.getHeader("userBh");
        QxglUser user = qxglUserService.getById(userBh);
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        QueryWrapper<KeyValue> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(KeyValue::getKeycode, "xmlx");
        queryWrapper.lambda().eq(KeyValue::getKeyvalue, cxcyXm.getXmXmlxbh());
        KeyValue one = keyValueService.getOne(queryWrapper);
        cxcyXm.setXmXmlxmc(one.getKeyname());

        String xmbh = (cxcyXm.getXmBh() == null || "".equals(cxcyXm.getXmBh())) ? UUIDUtil.getUUID8("P", 2) : cxcyXm.getXmBh();
        cxcyXm.setXmBh(xmbh);
        user.setXmBh(xmbh);
        user.setXmMc(cxcyXm.getXmMc());
        boolean update = qxglUserService.updateById(user);

        String cz = "";
        if ("save".equals(cxcyXm.getCzbz())) {

            cxcyXm.setXmXgrbh(userBh);
            cxcyXm.setXmXgrmc(user.getUserMc());
            cxcyXm.setXmXgsj(format.format(date));
            cxcyXm.setXmSsxy(user.getUserXymc());
            cz = "项目基本信息保存";
        } else if ("shenbao".equals(cxcyXm.getCzbz())) {
            cxcyXm.setXmTbrbh(userBh);
            cxcyXm.setXmTbrmc(user.getUserMc());
            cxcyXm.setXmTbsj(format.format(date));
            cxcyXm.setXmSsxy(user.getUserXymc());
            cxcyXm.setXmzt("0");
            cxcyXm.setXmSsxy(user.getUserXymc());
            cz = "项目申报";
        }

        QueryWrapper<CxcyXm> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(CxcyXm::getXmMc,cxcyXm.getXmMc());
        CxcyXm one1 = cxcyXmService.getOne(wrapper);
        if (one1 !=null && !one1.getXmBh().equals(xmbh)){
            throw new NormalException("该项目名称已有其他项目团队申报，请重新输入！");
        }

        boolean save = cxcyXmService.saveOrUpdate(cxcyXm);
        List<XmCy> xmCyList = cxcyXm.getXmCyList();
        QueryWrapper<XmCy> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(XmCy::getXmBh, xmbh);
        boolean remove = xmCyService.remove(queryWrapper1);

        for (XmCy xmCy : xmCyList) {
            xmCy.setXmBh(cxcyXm.getXmBh());
        }
        boolean b = xmCyService.saveBatch(xmCyList);
        if (!save && !b) {
            throw new NormalException(cz + "失败");
        }
        return Result.success(cz + "成功", cxcyXm);
    }

    @ApiOperation("上传项目计划书")
    @RequestMapping("fileUpload")
    public String fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request, String xmBh) {
        QueryWrapper<CxcyXm> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(CxcyXm::getXmBh, xmBh);
        CxcyXm cxcyXm = cxcyXmService.getOne(wrapper);

        try {
            byte[] bytes = file.getBytes();
            String fileName = file.getOriginalFilename();
            String url = environment.getProperty("front-assert-url.jhsdz");
            Path path = Paths.get(url + fileName);
            File file1 = new File(url + fileName);
            if (file1.exists() && !Objects.equals(fileName, "Template.docx")) {
                if (file1.delete()) {
                    System.out.println(fileName + "文件删除成功！");
                }
            }

            String yyxmJhsdz = cxcyXm.getXmJhsdz();
            File file2 = new File(url + yyxmJhsdz);
            if (file2.exists() && !Objects.equals(fileName, "Template.docx") && yyxmJhsdz != null) {
                if (file2.delete()) {
                    System.out.println(yyxmJhsdz + "文件删除成功！");
                }
            }
            Files.write(path, bytes);//写入文件
            String jhsdz = fileName;
            cxcyXm.setXmJhsdz(jhsdz);
            boolean b = cxcyXmService.updateById(cxcyXm);

            System.out.println(fileName + "\n");
            return fileName;//返回文件名字
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


    @ApiOperation("修改创新创业项目信息")
    @PostMapping("/updateCxcyXmByBh")
    @Transactional
    public Result updateCxcyXmByBh(@RequestBody CxcyXm cxcyXm) {
        boolean save = cxcyXmService.updateById(cxcyXm);
        if (!save) {
            throw new NormalException("修改创新创业项目信息失败");
        }
        return Result.success("修改创新创业项目信息成功", cxcyXm);
    }

    @ApiOperation("初筛")
    @PostMapping("/chushai")
    @Transactional
    public Result chushai(@RequestBody CxcyXm cxcyXm, HttpServletRequest request) {
        String userBh = request.getHeader("userBh");
        QxglUser user = qxglUserService.getById(userBh);
        cxcyXm.setXmCsr(userBh);
        cxcyXm.setXmCsrmc(user.getUserMc());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        cxcyXm.setXmCssj(format.format(new Date(System.currentTimeMillis())));

        if ("2".equals(cxcyXm.getXmzt())) {
            cxcyXm.setXmBhly(cxcyXm.getXmCsyj());
        }
        boolean save = cxcyXmService.updateById(cxcyXm);
        if (!save) {
            throw new NormalException("修改创新创业项目信息失败");
        }
        return Result.success("修改创新创业项目信息成功", cxcyXm);
    }

    @ApiOperation("路演录入")
    @PostMapping("/luYanLuRu")
    @Transactional
    public Result luYanLuRu(@RequestBody CxcyXm cxcyXm, HttpServletRequest request) {
        String userBh = request.getHeader("userBh");
        QxglUser user = qxglUserService.getById(userBh);
        cxcyXm.setXmPflr(userBh);
        cxcyXm.setXmPflrmc(user.getUserMc());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        cxcyXm.setXmLyqklrsj(format.format(new Date(System.currentTimeMillis())));

        if ("4".equals(cxcyXm.getXmzt())) {
            cxcyXm.setXmBhly(cxcyXm.getXmCsyj());
        }
        boolean save = cxcyXmService.updateById(cxcyXm);
        if (!save) {
            throw new NormalException("修改创新创业项目信息失败");
        }
        return Result.success("修改创新创业项目信息成功", cxcyXm);
    }

    @ApiOperation("审批")
    @PostMapping("/approval")
    @Transactional
    public Result approval(@RequestBody CxcyXm cxcyXm, HttpServletRequest request) {
        String userBh = request.getHeader("userBh");
        QxglUser user = qxglUserService.getById(userBh);
        cxcyXm.setXmSpr(userBh);
        cxcyXm.setXmSprmc(user.getUserMc());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        cxcyXm.setXmSpsj(format.format(new Date(System.currentTimeMillis())));
        cxcyXm.setXmRzsj(format.format(new Date(System.currentTimeMillis())));
        if ("6".equals(cxcyXm.getXmzt())) {
            cxcyXm.setXmBhly(cxcyXm.getXmCsyj());
        }
        boolean save = cxcyXmService.updateById(cxcyXm);
        if (!save) {
            throw new NormalException("修改创新创业项目信息失败");
        }
        return Result.success("修改创新创业项目信息成功", cxcyXm);
    }

    @ApiOperation("删除创新创业项目信息")
    @GetMapping("/deleteCxcyXmByBh")
    @Transactional
    public Result deleteCxcyXmByBh(String xmBh) {
        boolean remove = cxcyXmService.removeById(xmBh);
        if (!remove) {
            throw new NormalException("删除创新创业项目信息失败");
        }
        return Result.success("删除创新创业项目信息成功", xmBh);
    }

}

